const STS = require('qcloud-cos-sts')
var config = {
    secretId: 'AKIDXxBFE8vYzFH5jHsNfw52mSyHPL6czISa',
    secretKey: '2pNhmgN0UlpkRvBD3kDSYQ3SdcUCj6JL',
    proxy: '',
    durationSeconds: 1800,
    // 放行判断相关参数
    bucket: 'technique-1251242649',
    region: 'ap-beijing',
    allowPrefix: '*', // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
    // 简单上传和分片，需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
    allowActions: [
        // 简单上传
        'name/cos:PutObject',
        'name/cos:PostObject',
        // 分片上传
        'name/cos:InitiateMultipartUpload',
        'name/cos:ListMultipartUploads',
        'name/cos:ListParts',
        'name/cos:UploadPart',
        'name/cos:CompleteMultipartUpload'
    ],
};

exports.getoss = async () => {
    // 获取临时密钥
    var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
    var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
    var policy = {
        'version': '2.0',
        'statement': [{
            'action': config.allowActions,
            'effect': 'allow',
            'principal': {'qcs': ['*']},
            'resource': [
                'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
            ],
        }],
    };
    let result = {}
     const tempKeys = await  STS.getCredential({
        secretId: config.secretId,
        secretKey: config.secretKey,
        proxy: config.proxy,
        durationSeconds: config.durationSeconds,
        policy: policy,
    });
    result =  {
        SecretId: config.secretId,
        SecretKey:  config.secretKey,
        TmpSecretId: tempKeys.credentials.tmpSecretId,
        TmpSecretKey: tempKeys.credentials.tmpSecretKey,
        stsToken: tempKeys.credentials.sessionToken,
        ExpiredTime: tempKeys.expiration
    }
    return result
}

exports.getcos = (req, res) => {
    var shortBucketName = config.bucket.substr(0, config.bucket.lastIndexOf('-'));
    var appId = config.bucket.substr(1 + config.bucket.lastIndexOf('-'));
    var policy = {
        'version': '2.0',
        'statement': [{
            'action': config.allowActions,
            'effect': 'allow',
            'principal': {'qcs': ['*']},
            'resource': [
                'qcs::cos:' + config.region + ':uid/' + appId + ':prefix//' + appId + '/' + shortBucketName + '/' + config.allowPrefix,
            ],
        }],
    };
    STS.getCredential({
        secretId: config.secretId,
        secretKey: config.secretKey,
        proxy: config.proxy,
        durationSeconds: config.durationSeconds,
        policy: policy,
    }, function (err, tempKeys) {
        var result = JSON.stringify(err || tempKeys) || '';
        res.send({
            data: tempKeys
        });
    });
}
